/**
 * Alarm is generic, it will set off a basic alarm based on information
 * and will setup as a Critical Alarm given certain criteria.
 * 
 * This is a state based class
 */
package bedside;

import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.List;
import java.io.Serializable;
import common.AlarmReceiver;

public class Alarm implements Serializable {
	
	//Class Constants
	final static int HIGH_HIGH = 0;
	final static int HIGH = 1;
	final static int NORMAL = 2;
	final static int LOW = 3;
	final static int LOW_LOW = 4;
	
	//Class Variables
	int myMode;
	List<AlarmReceiver> myAR;
	int myID;
	
	//Static Class Variable
	static Integer ID = 0;
	
	/**
	 * Basic Instantiation
	 */
	public Alarm(){
		synchronized(ID){
			myID = ID;
			ID = ID + 1;
		}
		myMode = NORMAL;
		myAR = new LinkedList<AlarmReceiver>();
	}
	
	public void setState(int newState){
		if( myMode != newState ){
			myMode = newState;
			this.alertAll();
		}
	}
	
	public void reset(){
		myMode = Alarm.NORMAL;
		this.alertAll();
	}
	
	public boolean isCriticalAlarm(){
		return (myMode == Alarm.HIGH_HIGH || myMode == Alarm.LOW_LOW);
	}
	
	public boolean isAlarm(){
		return (myMode == Alarm.HIGH || myMode == Alarm.LOW);
	}
	public boolean isNormal(){
		return (myMode == Alarm.NORMAL);
	}
	public int getMyID(){
		return myID;
	}
	
	private void alertAll(){
		for( AlarmReceiver theAR : myAR ){
			try {
				theAR.alarmTriggered(this);
			} catch (RemoteException e) {
				System.out.println( "CLASS: Alarm METHOD: alertAll EXCEPTION:" + e.getMessage() );
				e.printStackTrace();
			}
		}
	}
	
	public void register(AlarmReceiver newItem){
		this.myAR.add(newItem);
	}
	public void unRegister(AlarmReceiver takeMe){
		this.myAR.remove(takeMe);
	}
}
